package org.ju.jms.p2p;

import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

public class AsynchronousReceiver implements MessageListener {

	public static void main(String[] args) throws Exception {
		Properties props = new Properties();
        props.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
        props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
        props.setProperty("java.naming.provider.url", "localhost:1099");
        Context ctx = new InitialContext(props); 
        
        QueueConnectionFactory cf = (QueueConnectionFactory)ctx.lookup("QueueConnectionFactory");
        Queue q = (Queue)ctx.lookup("queue/testQueue");
        QueueConnection con = cf.createQueueConnection();
        con.start();
        try{
        	QueueSession session = con.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        	QueueReceiver receiver = session.createReceiver(q);
        	receiver.setMessageListener(new AsynchronousReceiver());
        	while(true){
        		System.out.println("Doing other tasks.....");
        		Thread.sleep(5000);
        	}
        }catch (Exception e) {
			e.printStackTrace();
		}finally{
			con.close();
		}
	}

	
	public void onMessage(Message m){
		try {
			System.out.println("Got Message : "+((TextMessage)m).getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}

}
